"""
multiple process to execute commands
"""
import math
import multiprocessing

from .execute import execute


def process(command):
    logs = []
    if type(command) == list:
        for command_str in command:
            exec_log = execute(command_str)
            logs.append(exec_log)
    elif type(command) == str:
        exec_log = execute(command)
        logs.append(exec_log)
    else:
        pass

    return logs


def multi_process(commands, cores, logger):
    def write_log(logs:list):
        for log_item in logs:
            func = getattr(logger, log_item["type"])
            func(log_item["context"])

    if len(commands) <= cores:
        pools = multiprocessing.Pool(len(commands))
        for command in commands:
            pools.apply_async(
                func=process,
                args=(command,),
                callback=write_log
            )
        pools.close()
        pools.join()
    else:
        pools = multiprocessing.Pool(cores)
        core_sample_num = math.ceil(len(commands) / cores)
        for i in range(cores):
            command_set = commands[i*core_sample_num:(i+1)*core_sample_num]
            pools.apply_async(
                func=process,
                args=(command_set,),
                callback=write_log
            )
        pools.close()
        pools.join()
